package com.smartguard.dao;


import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.smartguard.datasource.MongoConnection;
import com.smartguard.util.PojoUtil;


public class BaseDAOImpl implements BaseDAO {

	@Override
	public <T> List<T> find(T pojo, int num) {
		DB db = MongoConnection.getDB();
		
		String collectionName = pojo.getClass().getSimpleName();
		DBCollection collection = db.getCollection(collectionName);
		DBObject ref = PojoUtil.Pojo2DBObject(pojo);
		DBCursor cursor = collection.find(ref);
		
		List<T> tList = new LinkedList<T>();
		
		//-1表示取到尽头
		if(num == -1){
			while(cursor.hasNext()){
				DBObject dbObject = cursor.next();
				tList.add((T)PojoUtil.DBObject2Pojo(dbObject, pojo.getClass()));
			}
		}
		else{
			int count = 0;
			while(cursor.hasNext() && count < num){
				DBObject dbObject = cursor.next();
				tList.add((T)PojoUtil.DBObject2Pojo(dbObject, pojo.getClass()));
				count++;
			}
		}
		
		return tList;
	}
	
	@Override
	public <T> T findOne(T pojo) {
		DB db = MongoConnection.getDB();
		String collectionName = pojo.getClass().getSimpleName();
		DBCollection collection = db.getCollection(collectionName);
		DBObject ref = PojoUtil.Pojo2DBObject(pojo);
		
		DBObject dbObject = collection.findOne(ref);
		T resultPojo = (T) PojoUtil.DBObject2Pojo(dbObject, pojo.getClass());
		return resultPojo;
	}

	@Override
	public <T> int delete(T pojo) {
		DB db = MongoConnection.getDB();
		String collectionName = pojo.getClass().getSimpleName();
		DBCollection collection = db.getCollection(collectionName);
		DBObject dbObject = PojoUtil.Pojo2DBObject(pojo);
		int n = collection.remove(dbObject).getN();
		return n;
	}
	
	@Override
	public <T> int delete(T[] pojoArray){
		int n = 0;
		for(T pojo: pojoArray){
			n += this.delete(pojo);
		}
		return n;
	}

	@Override
	public <T> boolean updateOne(T oldPojo, T newPojo) {
		DB db = MongoConnection.getDB();
		String collectionName = oldPojo.getClass().getSimpleName();
		DBCollection collection = db.getCollection(collectionName);
		DBObject oldDBObject = PojoUtil.Pojo2DBObject(oldPojo);
		DBObject newDBObject = PojoUtil.Pojo2DBObject(newPojo);
		if(collection.update(oldDBObject, newDBObject).getN() == 1){
			return true;
		}
		return false;
	}

	@Override
	public <T> boolean insert(T pojo) {
		try{
			DB db = MongoConnection.getDB();
			String collectionName = pojo.getClass().getSimpleName();
			DBCollection collection = db.getCollection(collectionName);
			DBObject dbObject = PojoUtil.Pojo2DBObject(pojo);
			WriteResult result = collection.insert(dbObject);
			//return result.getUpsertedId() == null ? true:false;
			return true;
		} catch(Exception e){
			return false;
		}
		
	}
	
}
